package com.feib.soeasy.job;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.jasperreports.engine.JRException;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.feib.soeasy.model.Group;
import com.feib.soeasy.model.Payment;
import com.feib.soeasy.model.UploadFile;
import com.feib.soeasy.model.User;
import com.feib.soeasy.service.GroupService;
import com.feib.soeasy.service.PaymentService;
import com.feib.soeasy.service.UploadFileService;
import com.feib.soeasy.util.SoezReportManager;
import com.lowagie.text.pdf.PdfCopyFields;
import com.lowagie.text.pdf.PdfReader;


@Service("createReportJob")
@Scope(value=BeanDefinition.SCOPE_PROTOTYPE)
public class CreateReportJob {
    public static Logger logger = LoggerFactory.getLogger(CreateReportJob.class);

    public static final SimpleDateFormat BASIC_DATE_TIME_FORMAT = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    @Resource(name="groupService")
    GroupService groupService;
    
    @Resource(name="paymentService")
    PaymentService paymentService;

    @Resource(name="uploadFileService")
    private UploadFileService uploadFileService;
    
    private User modifyUser;

    @Resource(name="reportTemplateDirectory")
    private String reportTemplateDirectory;

    public void execute(Long uploadFilePk)
    {
        try {
            UploadFile uploadFile = uploadFileService.getUploadFileByPk(uploadFilePk);
            String jrxmlPath = uploadFile.getFormatDefinition().getJrxmlPath();
            if (StringUtils.isEmpty(jrxmlPath))
            {
                // 空的就給default
                if (Group.GROUP_TYPE_SCHOOL.equals(uploadFile.getGroup().getGroupType()))
                {
                    jrxmlPath = reportTemplateDirectory + "/ycvsReport.jrxml";
                }
                else
                    jrxmlPath = reportTemplateDirectory +"/community.jrxml";
            }
            logger.debug("jrmxl path: {}", jrxmlPath);
            //黃郁珊 依中租需求修改
            Group group = uploadFile.getGroup();
            
            if(group != null && !group.getGroupType().equals(new Integer(4)))
            {
	            uploadFileService.updateUploadFileStatus(uploadFilePk, UploadFile.FILE_STATUS_CREATE_REPORT);
	            List<Long> list = paymentService.queryPaymentPkByUploadFilePk(uploadFilePk);	            
	
	            if(null != list && list.size() > 0)
	            {
	            	List<String> paymentPdfNames = new ArrayList<String>();
	                for(int i=0;i<list.size();i++)
	                {
	                    Payment payment = new Payment();
	                    payment.setPaymentPk(new Long(list.get(i)));
	                    payment = paymentService.getPaymentReport(payment);
	
	                    List<Payment> payments = new ArrayList<Payment>();
	                    payments.add(payment);
	
	                    Map<String,String> reportParameters =new HashMap<String,String>();
	                    
	                    File file = new File(jrxmlPath);
	                    String subreportDir = file.getParent(); 
	                    
	                    if (null == subreportDir)
	                        subreportDir = this.reportTemplateDirectory;
	                    logger.debug("sub report jrmxl path: {}", jrxmlPath);
	
	                    reportParameters.put("SUBREPORT_DIR", 
	                                    subreportDir.replaceAll("\\\\", "/") + "/");
	
	                    if (payment != null && payment.getPdfFilePathOnServer() != null){
	                    	SoezReportManager.exportReportToPdfFile(
		                                    jrxmlPath, 
		                                    reportParameters, 
		                                    payments, 
		                                    payment.getPdfFilePathOnServer().replaceAll("\\\\", "/") + "/");
		
		                    paymentPdfNames.add(payment.getPdfFilePathOnServer().replaceAll("\\\\", "/") + "/");
	                    }else{
	                    	logger.debug("uploadFilePk:{}", uploadFilePk);
	                    	if (null == payment){
 	                    	   	logger.debug("payment is null");
	                    	}else if (null == payment.getPdfFilePathOnServer()){
 	                    	    logger.debug("payment.getPdfFilePathOnServer() is null");
	                    	}    
	                    }
	                }
	
	                mergePDF(uploadFile.getPdfFilePathOnServer().replaceAll("\\\\", "/") + "/", paymentPdfNames);
	            }
            }else if(group != null && group.getGroupType().equals(new Integer(4)))
            {
            	uploadFileService.updateUploadFileStatus(uploadFilePk, UploadFile.FILE_STATUS_CREATE_REPORT);
            	Map reportParameters =new HashMap();
            	List<String> payerIds = paymentService.queryPayerIdByUploadFilePk(uploadFilePk);
            	List<String> paymentPdfNames = new ArrayList<String>();
            	for(int i=0;i<payerIds.size();i++)
            	{
            		String payerId = (String)payerIds.get(i);
            		List<Payment> payments = paymentService.queryPayementByPayerId(payerId, uploadFilePk);
			
					if (0 ==payments.size())
					{
						logger.error("uploadFilePk:{}", uploadFilePk);
						logger.debug("合約編號 {} 查無繳費資料資料", payerId);
						continue;
					}
			
            		Payment payment = payments.get(0);
                	String pdfFilePathOnServer = payment.getPdfFilePathOnServer();
			
					if (null == pdfFilePathOnServer)
					{
						logger.error("uploadFilePk:{}", uploadFilePk);
						logger.debug("PaymentPk= [{}] 的 欄位[pdfFilePathOnServer]為空值", payment.getPaymentPk());
						continue;
					}
                	
                	Long totalPayAmount = new Long(0);
                	for(int j=0;j<payments.size();j++)
                	{
                		Payment pa = (Payment)payments.get(j);
                		totalPayAmount = totalPayAmount + pa.getTotalAmount();
                		pa.getExtraColumns().setAttribute20(String.valueOf(j+1));
                		
                		//大於60000 則不顯示超商繳費
                		if(pa.getTotalAmount().intValue() > 60000)
                			pa.getExtraColumns().setAttribute19("1");
                		else
                			pa.getExtraColumns().setAttribute19("2");
                	}
                	
                	reportParameters.put("payment", payment);
                	reportParameters.put("totalPayAmount", totalPayAmount); //貸款金額
                	reportParameters.put("payCount", payerIds.size());
                	
                	
                	SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
                	reportParameters.put("printDate", dateFormat.format(new Date()));
                	
                	
					SoezReportManager.exportReportToPdfFile(
					    jrxmlPath, 
					    reportParameters, 
					    payments, 
					    pdfFilePathOnServer.replaceAll("\\\\", "/") + "/");
					
					paymentPdfNames.add(payment.getPdfFilePathOnServer().replaceAll("\\\\", "/") + "/");
		                	
            	}
            	
            	mergePDF(uploadFile.getPdfFilePathOnServer().replaceAll("\\\\", "/") + "/", paymentPdfNames);
            	

            }
            
            uploadFile.setFileStatus(UploadFile.FILE_STATUS_CONFIRM_OK);
            paymentService.updatePaymentStatusByUploadFile(uploadFile, modifyUser);
        } catch (JRException e ) {
            throw new RuntimeException("繳費單產出錯誤：", e);
        }
    }


    public void mergePDF(String uploadFilePdfName, List<String> paymentPdfNames)
    {
        try {
            PdfCopyFields copy = new PdfCopyFields(new FileOutputStream(uploadFilePdfName));
            copy.open();
            String pageNOs = "";

            for(int i=0;i<paymentPdfNames.size();i++)
            {
                PdfReader reader = 
                    new PdfReader(String.valueOf(paymentPdfNames.get(i)));
                int noOfPages = reader.getNumberOfPages();

                if (noOfPages > 0) 
                {
                    pageNOs = getNumderOfPages(noOfPages);
                }
                copy.addDocument(reader, pageNOs);              

            }
            copy.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public String getNumderOfPages(int noOfPages) {
        String pageNOs = "";
        boolean flag = false;
        for (int i = 0; i < noOfPages; i++) {

            if (flag == true) {
                Integer c = (Integer) i;
                pageNOs = pageNOs.concat("," + c.toString());
            }
            if (flag == false) {
                Integer c = (Integer) i;
                pageNOs = c.toString();
                flag = true;
            }
        }
        return pageNOs;
    }


    public PaymentService getPaymentService() {
        return paymentService;
    }


    public void setPaymentService(PaymentService paymentService) {
        this.paymentService = paymentService;
    }


    
    /**
     * @return the modifyUser
     */
    public User getModifyUser() {
        return modifyUser;
    }


    
    /**
     * @param modifyUser the modifyUser to set
     */
    public void setModifyUser(User modifyUser) {
        this.modifyUser = modifyUser;
    }

}
